import Vue from 'vue'
import VueRouter from 'vue-router'
// 引入仓库内容
import store from '../store'

//封装一个判断当前模块是否有权限方法
function hasUrl(url,next){
  //判断当前地址是否在信息menus数组中，在就放行，不在就拦截，强制跳转首页
  // console.log(store.getters);
  let result = store.getters.getUser.menus_url.some((item) => url === item);
  if(result){
    next()
  }else{
    next('/home')
  }
}

Vue.use(VueRouter)

   export const IndexRouter=[
    {
      path:'/menu',
      component:()=>import('../view/menu/menu.vue'),
      meta:{
        title:'菜单管理'
      },
      beforeEnter(to, from, next){
        hasUrl("/menu",next)
      }
    },{
      path:'/role',
      component:()=>import('../view/role/role.vue'),
      meta:{
        title:'角色管理'
      },
      beforeEnter(to, from, next){
        hasUrl("/role",next)
      }
    },{
      path:'/admin',
      component:()=>import('../view/admin/admin.vue'),
      meta:{
        title:'管理员管理'
      },
      beforeEnter(to, from, next){
        hasUrl("/admin",next)
      }
    },{
      path:'/cate',
      component:()=>import('../view/cate/cate.vue'),
      meta:{
        title:'商品分类'
      }
    },{
      path:'/specs',
      component:()=>import('../view/specs/specs.vue'),
      meta:{
        title:'商品规格'
      }
    },{
      path:'/goods',
      component:()=>import('../view/goods/goods.vue'),
      meta:{
        title:'商品管理'
      }
    },{
      path:'/member',
      component:()=>import('../view/member/member.vue'),
      meta:{
        title:'会员列表'
      }
    },{
      path:'/banner',
      component:()=>import('../view/banner/banner.vue'),
      meta:{
        title:'轮播图列表'
      }
    },{
      path:'/seck',
      component:()=>import('../view/seck/seck.vue'),
      meta:{
        title:'秒杀列表'
      }
    }
   ]
const routes = [
  {
    path:'*',
    redirect:"/index"
  },
  {
    path:'/login',
    component:()=>import('../pages/login.vue')
  },{
    path:'/index',
    component:()=>import('../pages/index.vue'),
    children:[
      {
        path:'',
        redirect:'/home'
      },
      {
        path:'/home',
        component:()=>import('../view/home.vue')
      },
      ...IndexRouter,
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 封装全局登录事件
router.beforeEach((to, from, next) => {
  // console.log(to)
  // next();
  // // 1、先检测用户访问的地址是否是登录
  if (to.path == "/login") {
    next();
    return;
  } 
  // //2、判断用户是否登录
  if (store.state.userInfo) {
    next();
    return;
  }               
  
  //3、如果未登录 就强制跳转到登录
  next("/login");
  // next()
})


export default router
